﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using RBS.Common;
using RBS.Common.JsonEntity;
using RBS.Core.Model;
using RBS.Web.Models;
using System.Data;
using RBS.Core.Extension;
namespace RBS.Web.Controllers
{
    public class StoreController : BaseController
    {
        //
        // GET: /Store/ 
        public ActionResult Index(int id, int orderid=0)
        {
            var model = new RBS.Core.BLL.Hotel.H_Hotels().GetModel(id);
            ViewBag.orderid = orderid;
            if (orderid != 0)
            {
                var bll = new RBS.Core.BLL.D_Order_Details();
                if (bll.ExistsOrderId(orderid, CurrentUser.Id))
                {
                    var items = bll.GetModelList(" orderid=" + orderid + " and uid=" + CurrentUser.Id); 
                    Session[RBSKeys.SESSION_SHOPCAR_INFO] = items;
                    ViewBag.orderid = orderid;
                } 
            } 
            return View(model);
        }

        #region 手机Apk页面
        public ActionResult ApiIndex(int id)
        {
            ViewBag.hotelId = id;  
           // var apiHotelSeat= new RBS.Core.BLL.SpBll().GetApiHotelSeat(id, DateTime.Now);
          //  ViewBag.ApiHotelSeat = string.Format(" <dd class=\"yede\">有<b>{0}</b>人预定 剩余<b>{1}</b>台（平均翻台时间20分钟）</dd> ", apiHotelSeat.已预定, apiHotelSeat.剩余);
            return View();
        }
        public ActionResult ApiHead(int id)
        {
            ViewBag.hotelId = id; 
            return View();
        }
        #endregion
        #region 酒店列表

        public ActionResult List(string category=null,string  keyword=null )
        {
           ViewBag.category = category;
           ViewBag.keyword = keyword; 
           ViewBag.stcript = "$(\"#schbtn\").submit();"; 
            return View();
        }
        [HttpPost]
        public JsonResult List(FormCollection formCollection)
        {
            string where = "?city=上海";
            where += "&type=0";
            where += "&category=" + formCollection["category"];
            where += "&keyword=" + formCollection["keyword"];
            where += "&limit=20";
            /*   where += "&region=" + formCollection["region"];*/
            where += "&sort=" + formCollection["sort"];
            var jsonData = RBS.Web.Models.ApiRepository.Get("api/hotel/SelectHotel" + where);
            return Json(jsonData);
        }
        #endregion

        #region 订单

        public ActionResult Order(int hotelid, int orderid=0)
        {
            if (User.Identity.Name == "")
            {
                return RedirectToAction("Index", "Login", new { redirectUrl = Request.Url });
            } 
            var user = CurrentUser;
            var model = new RBS.Core.Model.D_Order
            {
                H_Id = hotelid,
                ContactUser = user.U_Name,
                ContactMobile = user.Mobile
            };
            ViewBag.DineTable = "";
            if (orderid != 0)
            {
                model = new RBS.Core.BLL.D_Order().GetModelList(" Id="+orderid+"and U_Id="+CurrentUser.Id).FirstOrDefault();
                if (model != null && model.OrderState > 3)
                {
                    return RedirectToAction("Error", "Home");
                }
                if (model != null) ViewBag.DineTable = model.DineTable;
            }
            return View(model);
        }
       /* [HttpPost]
        public ActionResult Order(FormCollection collection)
        {

            //修改订单
            var oid = AddOrder(collection);
            var uid = Convert.ToInt32(User.Identity.Name);

            //修改桌位信息  
            UpdateSeatStatus(collection["DineTable"], collection["OldDineTable"], int.Parse(collection["H_Id"])); 
            //修改菜单
            UpdateDetail(oid, uid);  
            return RedirectToAction("OrderList", "Order", new { area = "User" }); 
            return View();
        }*/ 
        public ActionResult OrderTemp(int hotelid, int orderid = 0)
        { 
            //修改订单 
            var uid = Convert.ToInt32(User.Identity.Name); 
            //修改菜单
            if (orderid > 0)
            {
                UpdateDetail(orderid, uid);
                new RBS.Core.BLL.D_Order().UpdateOrderStatus(orderid, (int) RBS.Common.RBSEnums.OrderStatus.Ok);
                return RedirectToAction("OrderSubmit", new {hotelid = hotelid, orderid = orderid});
            }
            else
            {
                return RedirectToAction("Error","Home");
            }
        }

        public ActionResult OrderSubmit(int hotelid, int orderid = 0)
        {
            try
            {
                // if(CurrentUser.U_Uid) 
                //酒店信息
                var model = new RBS.Core.BLL.Hotel.H_Hotels().GetModel(hotelid);
                if (model == null) return RedirectToAction("Error", "Home");

                var userOrder = new RBS.Web.Models.UserOrder {Hotel = model};
                //订单
                var order = new RBS.Core.BLL.D_Order().GetModelList(" Id=" + orderid).FirstOrDefault();
                userOrder.Order = order;
                //菜单
                var orderDetails = new RBS.Core.BLL.V_OrderDetails().GetModelList(" orderid=" + orderid);
                userOrder.OrderDetails = orderDetails;
                //邀请的客人
                var orderGuest = new RBS.Core.BLL.D_Guest().GetModelList(" orderid=" + orderid);
                userOrder.OrderGuest = orderGuest;
              /*  //用户优惠券
                int count = 0;
                DataTable dt =
                    new RBS.Core.BLL.P_Advertis_Payment().GetListByUser(10, 1,
                                                                        "and U_Id= " + order.U_Id + " and HotelId=" +
                                                                        order.H_Id + "  and ValidEndTime>=GETDATE()",
                                                                        " ValidEndTime desc ", out count).Tables[0];
                IListDataSet.DataTableToIList<RBS.Core.Model.P_Advertis_Payment>(dt);
                userOrder.UserDeed = IListDataSet.DataTableToIList<RBS.Core.Model.P_Advertis_Payment>(dt);
                //用户积分
                userOrder.UserIntegration = new RBS.Core.BLL.U_User_Integration().GetIntegralCount(order.U_Id);*/
                //OrderGuest
                return View(userOrder);
            }
            catch 
            {
                return RedirectToAction("Error", "Home");
            }
        }

        [HttpPost]
        public ActionResult OrderSubmit(FormCollection collection)
        {

            //跳转到用用户订单列表
            return RedirectToActionPermanent("OrderList", "Order", new {area = "User"});
        }


        [HttpPost]
        public ActionResult Order(FormCollection collection)
        {
            //修改订单
            var oid = AddOrder(collection);
            var uid = Convert.ToInt32(User.Identity.Name);
            //修改桌位信息  
           // UpdateSeatStatus(collection["DineTable"], collection["OldDineTable"], int.Parse(collection["H_Id"]));
            //修改菜单
            //UpdateDetail(oid, uid);  
            //return RedirectToAction("OrderList", "Order", new { area = "User" }); 
            return Content(oid.ToString());
        } 
        public void UpdateDetail(int orderId,int uid)
        { 
                var bll = new RBS.Core.BLL.D_Order_Details(); 
              /*  var items = bll.GetModelList(" OrderId=" + orderId);  
                foreach (var dOrderDetailse in items)
                {
                    bll.Delete(dOrderDetailse.Id);
                }*/ 

                var Olditems = bll.GetModelList(" OrderId=" + orderId);
                var detailTemp = (List<RBS.Core.Model.V_OrderDetails>)Session[RBSKeys.SESSION_SHOPCAR_INFO];
               
                 foreach (var items in detailTemp)
                    {
                        V_OrderDetails items1 = items;
                        var item = Olditems.Where(c => c.HCId == items1.HCId && c.OrderId == items1.OrderId); 
                        var count = item.Count() - items1.Num; 
                    if (count > 0)
                    { 
                        var deleteItem =
                          Olditems.Where(
                                c => c.HCId == items1.HCId && c.OrderId == items1.OrderId && c.State == 1);
                        for (int i = 0; i < count; i++)
                        {
                            bll.Delete(deleteItem.First().Id); 
                        }
                    }
                    else if (count < 0)
                    { 
                        //添加 
                        var cook =  new RBS.Core.BLL.Hotel.H_Hotel_Cookbook().GetModelByCache(items.HCId);
                        for (int i = count; i < 0; i++)
                        {
                            var orderTemp = new RBS.Core.Model.D_Order_Details
                            {
                                OrderId = orderId,
                                UId = uid,
                                HCId = items.HCId,
                                Num = 1, 
                                State = 1,
                                DisAmount = cook.Discount,
                                CName = cook.Name,
                                Price = cook.Price,
                                OperateDate = DateTime.Now
                            };
                            bll.Add(orderTemp); 
                        }
                    }  
                }  
            //订单创建成功后移除购物车信息
            Session.Remove(RBSKeys.SESSION_SHOPCAR_INFO);  
        }

        public void UpdateSeatStatus(string dineTable, string oldDineTable,int hotelId)
        {
            var bll = new RBS.Core.BLL.Hotel.H_Hotel_Seat();
            if(oldDineTable=="")
            {
                bll.UpdateStatus(hotelId, dineTable, 1);
            }
            else
            {
                if (oldDineTable != dineTable){
                bll.UpdateStatus(hotelId, dineTable, 1);
                bll.UpdateStatus(hotelId, oldDineTable, 0);
                }
            }
        }

        public int AddOrder(FormCollection collection)
        {
            var oid = -1;
            var a = collection;
            var model = new RBS.Core.Model.D_Order
            { 
                OrderChannel = "网站预定",
                ContactUser = collection["ContactUser"],
                ContactMobile = collection["ContactMobile"],
                OrderRemark = collection["OrderRemark"],
                ReserveDate = collection["ReserveDate"],
                ReserveTime = collection["ReserveTime"],
                DineNum = int.Parse(collection["DineNum"]),
                H_Id = int.Parse(collection["H_Id"]), 
                DineTable = int.Parse(collection["DineTable"]),
                Dinecondition = collection["Dinecondition"],
                PayTime = DateTime.Now,
                CreateTime = DateTime.Now,
                U_Id = Convert.ToInt32(User.Identity.Name),
                LastModifyDate = DateTime.Now 
            }; 
            model.OrderTime = Convert.ToDateTime(model.ReserveDate +" "+model.ReserveTime); 
            model.HotelName = new RBS.Core.BLL.Hotel.H_Hotels().GetModelByCache(model.H_Id).H_Name; 
            var bll = new RBS.Core.BLL.D_Order();
            try
            {
                if (collection["Id"] != "0")
                {
                    model.Id = Convert.ToInt32(collection["Id"]);
                    model.OrderState = 2;
                    bll.Update(model);
                    oid = model.Id;
                }
                else
                {
                    model.OrderState = 1;
                    oid = bll.Add(model);
                }
            }
            catch
            {
                oid = -1;
            }

            return oid;
        }


        #endregion

        #region 详情
        public ActionResult Detail(int id, int orderid)
        { 

            var model=new RBS.Core.BLL.Hotel.H_Hotels().GetModel(id);
            var userOrder = new RBS.Web.Models.UserOrder();
            userOrder.Hotel = model;

            var order   = new RBS.Core.BLL.D_Order().GetModelList(" Id="+orderid).FirstOrDefault();
            userOrder.Order = order;

            var orderDetails = new RBS.Core.BLL.V_OrderDetails().GetModelList(" orderid=" + orderid );
            userOrder.OrderDetails = orderDetails;  
            var orderGuest = new RBS.Core.BLL.D_Guest().GetModelList(" orderid=" + orderid); 
            userOrder.OrderGuest = orderGuest; 
            //OrderGuest
            return View(userOrder);
        }

       
        #endregion
        #region  APIS
        /// <summary>
        /// 点菜完成后修改状态
        /// </summary>
        /// <param name="orderid"></param>
        /// <returns></returns>
        public JsonResult UpdateOrder(int orderid)
        {
            JsonData jsonData = RBS.Web.Models.ApiRepository.Get("api/User/Order?orderid=" + orderid + "&status=2");
            return Json(jsonData);
        }

        /// <summary>
        /// 获取菜谱分类
        /// </summary>
        /// <param name="hid"></param>
        /// <returns></returns>
        public JsonResult GetCategory(int hid)
        {
            JsonData jsonData = RBS.Web.Models.ApiRepository.Get("api/hotel/Cookbook?hid=" + hid);
            return Json(jsonData); 
        }
        /// <summary>
        /// 获取菜谱
        /// </summary>
        /// <param name="hid"></param>
        /// <param name="cid"></param>
        /// <returns></returns>
        public JsonResult GetCookbook(int hid, int cid)
        {
            JsonData jsonData = cid == 0 ? RBS.Web.Models.ApiRepository.Get("api/hotel/Cookbook?type=Cookbook&hid=" + hid) : RBS.Web.Models.ApiRepository.Get("api/hotel/Cookbook?type=Cookbook&hid=" + hid + "&cid=" + cid);  
            return Json(jsonData);
        } 
        /// <summary>
        /// 座位
        /// </summary>
        /// <param name="hid"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public JsonResult GetSeat(int hid, string type)
        {
            JsonData jsonData = RBS.Web.Models.ApiRepository.Get("api/hotel/Seat?hid=" + hid + "&type=" + type); 
           //var  seat = jsonData.Data as List<RBS.Core.Model.Hotel.H_Hotel_Seat>; 
            return Json(jsonData);
        }
       /// <summary>
       /// 酒店图片
       /// </summary>
       /// <param name="hid"></param>
       /// <returns></returns>
        public JsonResult GetHotelImg(int hid)
        {
            JsonData jsonData = RBS.Web.Models.ApiRepository.Get("api/hotel/HotelImg/" + hid); 
            return Json(jsonData);
        }
        /// <summary>
        /// 菜系
        /// </summary>
        /// <returns></returns>
        public JsonResult GetCaiXi()
        {
            JsonData jsonData = RBS.Web.Models.ApiRepository.Get("api/dict/selectdict?type=child&dictcode=caixi");
            return Json(jsonData);
        } 

        
        #endregion

        /// <summary>
        /// 推荐食府
        /// </summary>
        /// <returns></returns>
        public JsonResult GetCommendHotel()
        {
            JsonData jsonData = new JsonData { Success = true };
            DataSet ds = new RBS.Core.BLL.Hotel.H_Hotels().GetListRecommend(5, " IsRecommend = 1", "pingfen");
            var list = new List<RBS.Core.Model.V_Hotel>();
            if (ds != null && ds.Tables[0] != null)
            {
                list.AddRange(from DataRow row in ds.Tables[0].Rows select row.ConvertToEntity<RBS.Core.Model.V_Hotel>());
            }
            jsonData.Data=list;
            return Json(jsonData);
        }
        /// <summary>
        /// 热门食府
        /// </summary>
        /// <returns></returns>
        public JsonResult GetHotHotel()
        {

            JsonData jsonData = new JsonData { Success = true };
            DataSet ds = new RBS.Core.BLL.Hotel.H_Hotels().GetListRecommend(5, " 1 = 1", "HotHotel");
            var list = new List<RBS.Core.Model.V_Hotel>();
            if (ds != null && ds.Tables[0] != null)
            {
                list.AddRange(from DataRow row in ds.Tables[0].Rows select row.ConvertToEntity<RBS.Core.Model.V_Hotel>());
            }
            jsonData.Data = list;
            return Json(jsonData);
        }

        /// <summary>
        /// 评论
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Comment(int id)
        {
            var model = new RBS.Core.BLL.Hotel.H_Hotels().GetModel(id);
            // var jsonData = ApiRepository.Get("api/User/Comment/" + id + "&type=hotel" + "&page=1&limit = 10");  
            return View(model);
           
        }
        /// <summary>
        /// 酒店图片
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult HotelImg(int id)
        {
            var model = new RBS.Core.BLL.Hotel.H_Hotels().GetModel(id);
            // var jsonData = ApiRepository.Get("api/User/Comment/" + id + "&type=hotel" + "&page=1&limit = 10");  
            return View(model);
        }
    }

 
}
